package cn.ysnk.clz.interceptor.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.RegexUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;

import cn.ysnk.clz.interceptor.security.role.RoleEnum;

public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource{

	public static void main(String[] args) {
		UrlMatcher urlMatcher = new RegexUrlPathMatcher();
		boolean isMatch = urlMatcher.pathMatchesUrl(urlMatcher.compile("(/menu)|(/menu(\\?)+.*)|(/menu/.*)"), "/menu/aa");
		System.out.println(isMatch);
	}
	
	private UrlMatcher urlMatcher = new RegexUrlPathMatcher();
	
	public static Map<String,Collection<ConfigAttribute>> resourceMap = null;
	
	public MySecurityMetadataSource(){
		resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
	}
	
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	public Collection<ConfigAttribute> getAttributes(Object obj) throws IllegalArgumentException {
		String url = ((FilterInvocation)obj).getRequestUrl();
		Iterator<String> ite = resourceMap.keySet().iterator();
		while(ite.hasNext()){
			String resUrl = ite.next();
			if(urlMatcher.pathMatchesUrl(urlMatcher.compile("("+resUrl+")|("+resUrl+"(\\?)+.*)|("+resUrl+"/.*)")	, url)){
				return resourceMap.get(resUrl);
			}
		}
		Collection<ConfigAttribute> roles =new ArrayList<ConfigAttribute>();
		roles.add(new SecurityConfig(RoleEnum.ROLE_USER.name()));
		return null;
	}

	public boolean supports(Class<?> clazz) {
		return FilterInvocation.class.isAssignableFrom(clazz);
	}

}
